using Consul;
using rpc_service.config;

namespace rpc_service.core.registry;

public class ConsulRegistry : Registry
{
    private readonly ConsulClient _client;
    private Dictionary<string, Services> _data;
    
    private static ConsulRegistry _instance = null;
    
    private ConsulRegistry(Config config)
    {
        _client = new ConsulClient(configure =>
        {
            configure.Address = new Uri(config.RegistryUrl);
        });
    }

    public static Registry GetInstance(Config config)
    {
        if (_instance == null)
        {
            _instance = new ConsulRegistry(config);
        }
        
        return _instance;
    }
    
    public Dictionary<string, Services> GetServices(bool isForce = false)
    {
        if (_data != null && !isForce)
        {
            return _data;
        }
        
        var serviceDictionary = _client.Agent.Services().Result.Response;
        var services = new Dictionary<string, Services>();
        foreach (var service in serviceDictionary)
        {
            string serviceName = serviceDictionary[service.Key].Service;
            string address = serviceDictionary[service.Key].Address;
            int port = serviceDictionary[service.Key].Port;

            if (!services.ContainsKey(serviceName))
            {
                Services tempServices = new Services()
                {
                    Index = 0,
                    ServiceList = new List<Service>()
                };
                services.Add(serviceDictionary[service.Key].Service, tempServices);
            }
            
            services[serviceName].ServiceList.Add(new Service()
            {
                Name = serviceName,
                Url = $@"{address}:{port}"
            });
        }
        
        _data = services;

        return _data;
    }
}